package com.jz.community.commview.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.ViewParent;

public class VerticalScrollViewPager extends ViewPager {

    private int mDownX;
    private int mDownY;

    public VerticalScrollViewPager(Context context) {
        super(context);
    }

    public VerticalScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FloatScrollView getRealParent() {
        ViewParent parent = getParent().
                getParent().getParent().
                getParent();
        if (parent != null && parent instanceof FloatScrollView) {
            return (FloatScrollView) parent;
        } else {
            return null;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        try {
            if (((ViewGroup) getParent()).getChildCount() <= 3) {
                return super.dispatchTouchEvent(ev);
            }

            int action = ev.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    mDownX = (int) (ev.getX() + 0.5f);
                    mDownY = (int) (ev.getY() + 0.5f);
                    if (getRealParent().getScrollY() < 50) {
                        getRealParent().scrollTo(0, 2);
                    }
                    getRealParent().requestDisallowInterceptTouchEvent(true);
                    break;
                case MotionEvent.ACTION_MOVE:
                    //不拦截,让子类自己消费
                    int mMoveX = (int) (ev.getX() + 0.5f);
                    int mMoveY = (int) (ev.getY() + 0.5f);
                    int disX = mMoveX - mDownX;
                    int disY = mMoveY - mDownY;
                    //垂直滑动,子类不消费
                    if (Math.abs(disY) > Math.abs(disX)) {
                        getRealParent().requestDisallowInterceptTouchEvent(false);
                    } else {
                        getRealParent().requestDisallowInterceptTouchEvent(true);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    //父类消费
                    getRealParent().requestDisallowInterceptTouchEvent(false);
                    break;
                default:
                    break;
            }
            return super.dispatchTouchEvent(ev);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        return false;
    }
}